<?php

namespace app\admin\controller\express;

use app\admin\model\express\OrderAddress;
use app\common\controller\Backend;
use app\common\model\Category;
use fast\Tree;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 订单
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{
    
    /**
     * Order模型对象
     * @var \app\admin\model\express\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\express\Order;
        $this->view->assign("statusList", $this->model->getStatusList());
        $tree = Tree::instance();
        $tree->init(collection(Category::order('weigh desc,id desc')->select())->toArray(), 'pid');
        $this->categorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');
        $this->assignconfig('categorydata',$this->categorylist);
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['user','address'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                $row->getRelation('user')->visible(['nickname','avatar']);
                $row->getRelation('address')->visible(['name','city','idcard','idcard_front','idcard_reverse']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $packages = $this->request->post('package/a');
            if ($packages) {
                $result = false;
                Db::startTrans();
                try {
                    if($row['status'] == 'package'){
                        $this->error('该订单已经生成包裹,不能重复生成');
                    }
                    $goodsList = $packageTrackData = [];
                    $deliveryPrice = 0;
                    foreach ($packages as $key => $item){
                        $package = new \app\admin\model\express\Package();
                        $package->order_id = $row['id'];
                        $package->user_id = $row['user_id'];
                        $package->address_id = OrderAddress::where([
                            'user_id' => $row['user_id'],
                            'order_id' => $row['id'],
                        ])->value('id');
                        $package->package_no = $row['order_no'].'-'.($key+1);
                        $package->delivery_price = $item['delivery_price'];
                        $package->express_com = $item['express_com'];
                        $package->express_no = $item['express_no'];
                        $deliveryPrice += $item['delivery_price'];
                        if($package->save()){
                            foreach ($item['goods'] as $goods){
                                $goodsList[] = [
                                    'package_id' => $package->id,
                                    'order_id' => $row['id'],
                                    'category_id' => $goods['category_id'],
                                    'name' => $goods['name'],
                                    'brand' => $goods['brand'],
                                    'sku' => $goods['sku'],
                                    'weight' => $goods['weight'],
                                    'number' => $goods['number'],
                                    'price' => $goods['price'],
                                    'rule_id' => $goods['rule_id'],
                                ];
                            }
                            $packageTrackData[] = [
                                'package_id' => $package->id,
                                'memo' => '准备发货',
                                'admin_id' => $this->auth->id,
                            ];
                        }

                    }

                    model('app\admin\model\express\PackageGoods')->saveAll($goodsList);

                    model('app\admin\model\express\PackageTrack')->saveAll($packageTrackData);
                    $params = [
                        'status' => 'package',
                        'delivery_price' => $deliveryPrice,
                        'delivery_address_id' => Db::name('express_delivery_address')->where('status','normal')->orderRaw('rand()')->value('id')
                    ];
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $comList = Db::name('express_com')->where('status','normal')->select();
        $address = model('app\admin\model\express\OrderAddress')->where('order_id',$row['id'])->find();
        $goods = model('app\admin\model\express\OrderGoods')->where('order_id',$row['id'])->column('*','id');
        $ruleList = model('app\admin\model\express\Rule')->all();
        $this->assignconfig('address',$address);
        $this->assignconfig('goods',$goods);
        $this->assignconfig('ruleList',$ruleList);
        $this->assignconfig('comList',$comList);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 分箱
     */
    public function goPackage(){
        $data = $this->request->post();
        $goodsList = [];
        foreach ($data['goods'] as $goods){
            if($goods['rule_id'] == 0){
                $this->error('请选择商品分箱规则');
            }
            $goodsList[] = [
                'id' => $goods['id'],
                'rule_id' => $goods['rule_id'],
                'category_id' => $goods['category_id'],
            ];
        }
        model('app\admin\model\express\OrderGoods')->saveAll($goodsList);
        $ruleList = model('app\admin\model\express\Rule')->all();
        $package = new \fast\Package($data['goods'],$ruleList);
        $packageList = $package->buildPackage();
        $list = [];
        foreach ($packageList as $item){
            $list = array_merge($list,$item);
        }
        $this->success('分箱成功','',$list);
    }

}
